<template>
  <a-row :gutter="4">
    <a-col :flex="2">
      <a-list item-layout="horizontal" :data-source="lstValueRule">
        <template #header>
          <a-button type="link" v-if="state.editMode == 0" @click="goNewRule">
            添加规则</a-button
          >
        </template>
        <template #renderItem="{ item }">
          <a-list-item
            class="ListItem"
            :class="{ active: item.selected }"
            @click="selectItem(item)"
          >
            <a-button type="link" danger @click="removeRule"
              ><DeleteOutlined
            /></a-button>
            {{ item.display }}
          </a-list-item>
        </template>
      </a-list>
    </a-col>
    <a-col :flex="3">
      <a-form :model="formLimit" layout="vertical">
        <a-form-item :label="$t('378')">
          <a-select
            v-model:value="formLimit.T"
            :disabled="state.editMode != 1"
            style="width: 200px"
          >
            <a-select-option
              v-for="x in appStore.aryRecordValueRuleDetail"
              :key="x.key"
              :value="x.key"
              >{{ x.label }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <FieldSelector
          v-if="formLimit.T == 11 || formLimit.T == 21"
          ref="refFieldSelector"
          :modelId="props.model.id"
          :multi="formLimit.T == 11"
          @ok="onFieldSelected"
        />
        <a-form-item v-if="formLimit.T == 21" label="限制的模型">
          <a-select v-model:value="formLimit.mid" style="width: 200px">
            <a-select-option
              v-for="x in lstModelsUseCurrentFiled"
              :key="x.id"
              :value="x.id"
              >{{ x.name }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item v-if="formLimit.T == 21" label="最少引用次数">
          <a-input-number v-model:value="formLimit.min"></a-input-number>
        </a-form-item>
        <a-form-item v-if="formLimit.T == 21" label="最多引用次数">
          <a-input-number v-model:value="formLimit.max"></a-input-number>
        </a-form-item>
        <FveEditor
          ref="refFvee"
          v-if="formLimit.T == 31"
          :single="true"
          :readonly="state.editMode < 1"
          :fields="state.fields"
          :inline="false"
        ></FveEditor>
        <a-button
          v-if="state.editMode == 1"
          type="primary"
          @click="saveNewRule"
        >
          保存修改</a-button
        >
      </a-form>
    </a-col>
  </a-row>
</template>
<script setup>
import { nextTick, reactive, ref, watch } from "vue";
import CommonDefine from "@/component/CommonDefine";
import FieldSelector from "@/component/field/FieldSelector.vue";
import { DeleteOutlined } from "@ant-design/icons-vue";
import FveEditor from "@/component/query/FveEditor.vue";

const props = defineProps({
  model: { type: Object, default: () => {} },
});
const appStore = CommonDefine.appStore();
const refFvee = ref();
const state = reactive({
  editMode: 0, // 0查看 1新建
  fields: [],
});

const lstValueRule = reactive([]);
const loadRecordRules = (modelId) => {
  state.editMode = 0;
  // 获取一下字段列表，防止缓存中没有
  let fn = (fields) => {
    state.fields = fields;
  };
  CommonDefine.runWithFieldCache(modelId, fn);
  CommonDefine.clearArray(lstValueRule);
  CommonDefine.apiGetArm("/api/v1/record/rvrs/" + modelId, (d) => {
    d.forEach((item) => {
      item.selected = false;
      item.display = appStore.aryRecordValueRuleDetail.find(
        (x) => x.key == item.detail.T
      ).label;
      lstValueRule.push(item);
    });
  });
};

const goNewRule = () => {
  state.editMode = 1;
};

const saveNewRule = () => {
  formLimit.modelId = props.model.id;
  if (formLimit.T == 21) {
    formLimit.fid = formLimit.ids[0];
  } else if (formLimit.T == 31) {
    Object.assign(formLimit, refFvee.value.getFves()[0]);
  }
  CommonDefine.apiPostArm("/api/v1/record/save-rvr", formLimit, (d) => {
    loadRecordRules(props.model.id);
  });
};

const refFieldSelector = ref();

const selectItem = (recordRule) => {
  lstValueRule.forEach((rule) => (rule.selected = false));
  recordRule.selected = true;
  // console.log(recordRule);
  let d = recordRule.detail;
  formLimit.T = d.T;
  if (formLimit.T == 11) {
    formLimit.ids = d.C;
    nextTick(() => {
      refFieldSelector.value.setSelected(formLimit.ids);
    });
  } else if (formLimit.T == 21) {
    formLimit.ids = [d.C.fieldId];
    Object.assign(formLimit, d.C);
    nextTick(() => {
      refFieldSelector.value.setSelected(formLimit.ids);
    });
  } else if (formLimit.T == 31) {
    nextTick(() => {
      refFvee.value.setFves([d.C]);
    });
  }
};

const removeRule = () => {
  lstValueRule.forEach((rule) => {
    if (rule.selected) {
      CommonDefine.apiPostArm("/api/v1/record/remove-rvr", rule, (d) => {
        loadRecordRules(props.model.id);
      });
    }
  });
};

const formLimit = reactive({});

const onFieldSelected = (selectedRowKeys) => {
  formLimit.ids = selectedRowKeys;
  if (formLimit.T == 21) {
    loadModelsLinkToFiled();
  }
};

const lstModelsUseCurrentFiled = reactive([]); // models which use selected field

const loadModelsLinkToFiled = () => {
  CommonDefine.clearArray(lstModelsUseCurrentFiled);
  if (formLimit.ids.length > 0) {
    CommonDefine.apiGetArm(
      `/api/v1/model/list-use-field/${formLimit.ids[0]}`,
      (lst) => {
        lst.forEach((item) => {
          lstModelsUseCurrentFiled.push(item);
        });
      }
    );
  }
};

watch(
  () => props.model,
  (newValue) => {
    state.editMode = 0;
    loadRecordRules(newValue.id);
  },
  {
    immediate: true,
  }
);
</script>
